package com.wanchuang.qhbb.view.pinnedheader;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Typeface;
import android.graphics.drawable.ColorDrawable;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.TextView;


import com.wanchuang.qhbb.R;

import java.util.ArrayList;
import java.util.List;

public class SideBar extends View {

    protected int mWidth = 100;
    protected int mHeight = 100;

    protected String TAG = this.getClass().getSimpleName();
    // 触摸事件
    private OnTouchingLetterChangedListener onTouchingLetterChangedListener;
    // 26个字母
    public List<String> b = new ArrayList<>();
    private int choose = -1;// 选中
    private Paint paint = new Paint();

    private TextView mTextDialog;
    private float singleHeight;
    public static int dialogColor[] = {R.drawable.dialog_color_blue};

    public void setTextView(TextView mTextDialog) {
        this.mTextDialog = mTextDialog;
    }

    public SideBar(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    private void init() {
        mHeight = 60 * b.size();
        Log.e("height", "init:" + mHeight);
    }

    public SideBar(Context context) {
        super(context);
    }


    /**
     * 测量View的大小，也可以通过下面方式，修改View的大小
     */

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        Log.e(TAG, "onMeasure: ");
        int width = getMeasureSize(true, widthMeasureSpec);
        int height = getMeasureSize(false, heightMeasureSpec);
        // setMeasuredDimension（） = 存储测量后的View宽 / 高
        setMeasuredDimension(width, height);
    }


    /**
     * 获取View尺寸
     * 基本上算是标准写法
     *
     * @param isWidth 是否是width，不是的话，是height
     */
    private int getMeasureSize(boolean isWidth, int measureSpec) {
        int result = 0;

        // 1. 获取测量模式（Mode）
        int specMode = MeasureSpec.getMode(measureSpec);

        // 2. 获取测量大小（Size）
        int specSize = MeasureSpec.getSize(measureSpec);

        switch (specMode) {
            case MeasureSpec.UNSPECIFIED:
                if (isWidth) {
                    result = getSuggestedMinimumWidth();
                } else {
                    result = getSuggestedMinimumHeight();
                }
                break;
            case MeasureSpec.AT_MOST:   // at_most中的specsize为子view可以拿到的最大值
                if (isWidth)
                    result = Math.min(specSize, mWidth);
                else
                    result = Math.min(specSize, mHeight);
                break;
            case MeasureSpec.EXACTLY:
                result = specSize;
                break;
        }
        Log.e("height", "getMeasureSize:" + mHeight);
        return result;
    }


    /**
     * 重写这个方法
     */
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        // 获取焦点改变背景颜色.
        int height = getHeight();// 获取对应高度
        int width = getWidth(); // 获取对应宽度

        // 获取每一个字母的高度
        singleHeight = (height * 1f) / b.size();
        singleHeight = (height * 1f - singleHeight / 2) / b.size();
        Log.e("height", "singleHeight:" + mHeight);
        for (int i = 0; i < b.size(); i++) {
            paint.setColor(Color.parseColor("#FF676E7D"));
            // paint.setColor(Color.WHITE);
            paint.setTypeface(Typeface.DEFAULT_BOLD);
            paint.setAntiAlias(true);
            paint.setTextSize(35);
            // 选中的状态
            if (i == choose) {
                paint.setColor(Color.parseColor("#c60000"));
                paint.setFakeBoldText(true);
            }

            // x坐标等于中间-字符串宽度的一半.
            float xPos = width / 2 - paint.measureText(b.get(i)) / 2;
            float yPos = singleHeight * i + singleHeight;
            if (b.size() == 1) {
                canvas.drawText(b.get(i), xPos, height, paint);
            } else {
                canvas.drawText(b.get(i), xPos, yPos, paint);
            }
            paint.reset();// 重置画笔
        }

    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent event) {
        final int action = event.getAction();
        final float y = event.getY();// 点击y坐标
        final int oldChoose = choose;
        final OnTouchingLetterChangedListener listener = onTouchingLetterChangedListener;
        final int c = (int) (y / getHeight() * b.size());// 点击y坐标所占总高度的比例*b数组的长度就等于点击b中的个数.

        switch (action) {
            case MotionEvent.ACTION_UP:
                setBackgroundDrawable(new ColorDrawable(0x00000000));
                choose = -1;//
                invalidate();
                if (mTextDialog != null) {
                    mTextDialog.setVisibility(View.INVISIBLE);
                }
                break;
            // 除开松开事件的任何触摸事件
            default:
//                setBackgroundResource(R.drawable.sidebar_background);
                if (oldChoose != c) {
                    if (c >= 0 && c < b.size()) {
                        if (listener != null) {
                            listener.onTouchingLetterChanged(b.get(c));
                        }
                        if (mTextDialog != null) {
                            mTextDialog.setText(b.get(c));
                            mTextDialog.setVisibility(View.VISIBLE);
                            // 动态改变文字dialog的位置
                            int right = mTextDialog.getLeft();
                            mTextDialog.setX(right / 2 * 3);
                            if (c > b.size()) {
                                mTextDialog.setY(singleHeight * b.size());
                            } else {
                                mTextDialog.setY(singleHeight * (c - 1) + getTop());
                            }
                            mTextDialog.setBackground(getContext().getResources().getDrawable(dialogColor[0]));
                        }

                        choose = c;
                        invalidate();
                    }
                }

                break;
        }
        return true;
    }

    /**
     * 向外公开的方法
     *
     * @param onTouchingLetterChangedListener
     */
    public void setOnTouchingLetterChangedListener(OnTouchingLetterChangedListener onTouchingLetterChangedListener) {
        this.onTouchingLetterChangedListener = onTouchingLetterChangedListener;
    }

    /**
     * 接口
     *
     * @author coder
     */
    public interface OnTouchingLetterChangedListener {
        public void onTouchingLetterChanged(String s);
    }

    public void setList(List<String> data) {
        b.clear();
        b.addAll(data);
        mHeight = b.size() * 45;
        Log.e("height", "setList:" + mHeight);
        forceLayout();
    }

}
